
// 手动实现一个兼容低版本的fetch
export default async(type = 'GET', url = '', data = {}, method = 'fetch') => {
	type = type.toUpperCase();
	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {

		/*
		credentials: 默认情况下, fetch 不会从服务端发送或接收任何 cookies，要发送 cookies，必须设置 credentials 选项。
			1. omit: 从不发送cookies.
			2. same-origin: 只有当URL与响应脚本同源才发送cookies.
			3. include: 总是发送cookies, 即使来自跨域的请求
		mode: 详见https://developer.mozilla.org/zh-CN/docs/Web/API/Request/mode
			其中cors — 允许跨域请求，例如访问第三方供应商提供的各种API。
		cache: https://developer.mozilla.org/zh-CN/docs/Web/API/Request/cache
			force-cache — The browser looks for a matching request in its HTTP cache.
				1. If there is a match, fresh or stale, it will be returned from the cache.
				2. If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.	
		 */
		let requestConfig = {		
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json', // 指定客户端能够接收的内容类型
				'Content-Type': 'application/x-www-form-urlencoded' // 不同内容的请求对应不同的值（eg. 设置value:applicating/x...  （无文件类型表单数据）； value:multipart/f...（含文件类型表单数据））-- 这边后台好像都可以适配
			},
			mode: "cors"
			// mode: "no-cors",
			// cache: "force-cache"
		}

		if (type == 'POST') {
			let formData  = new FormData();
			for(var name in data) {
			   formData.append(name, data[name]);
			}
			
			Object.defineProperty(requestConfig, 'body', {
				value : formData
			});
		}
		
		try {
			var response = await fetch(url, requestConfig);
			var responseJson = await response.json();
		} catch (error) {
			throw new Error(error)
		}
		return responseJson
	} else {
		let requestObj;
		if (window.XMLHttpRequest) {
			requestObj = new XMLHttpRequest();
		} else {
			requestObj = new ActiveXObject;
		}

		let sendData = '';
		if (type == 'POST') {
			sendData = JSON.stringify(data);
		}

		requestObj.open(type, url, true);
		requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		requestObj.send(sendData);

		requestObj.onreadystatechange = () => {
			if (requestObj.readyState == 4) {
				if (requestObj.status == 200) {
					let obj = requestObj.response
					if (typeof obj !== 'object') {
						obj = JSON.parse(obj);
					}
					return obj
				} else {
					throw new Error(requestObj)
				}
			}
		}
	}
}